cmake_minimum_required(VERSION 3.15)
project(DemoProject LANGUAGES CXX)

# 设置项目版本
set(PROJECT_VERSION_MAJOR 1)
set(PROJECT_VERSION_MINOR 0)
set(PROJECT_VERSION_PATCH 0)
set(PROJECT_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH})

# 设置 C++ 标准
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# 平台特定设置
if(WIN32)
    # Windows 设置
    set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)  # 自动导出符号
    add_compile_definitions(_CRT_SECURE_NO_WARNINGS)
    add_compile_definitions(NOMINMAX)  # 防止 min/max 宏冲突
    
    # 设置运行时库 (MT/MTd/MD/MDd)
    if(MSVC)
        set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL")
    endif()
else()
    # Linux/Unix 设置
    set(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif()

# 编译选项
# if(CMAKE_BUILD_TYPE STREQUAL "Debug")
#     add_compile_options(
#         "$<$<CXX_COMPILER_ID:MSVC>:/Zi /Od /MTd>"
#         "$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-g -O0 -Wall -Wextra -Wpedantic>"
#     )
# else()
#     add_compile_options(
#         "$<$<CXX_COMPILER_ID:MSVC>:/O2 /MT>"
#         "$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-O2 -Wall>"
#     )
# endif()

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    if(MSVC)
        add_compile_options(/Zi /Od /MTd)
    else()
        add_compile_options(-g -O0 -Wall -Wextra -Wpedantic)
    endif()
else()
    if(MSVC)
        add_compile_options(/O2 /MT)
    else()
        add_compile_options(-O2 -Wall)
    endif()
endif()

# 添加 cmake 模块路径
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")

# 设置库安装路径
if(WIN32)
    set(CMAKE_INSTALL_BINDIR "bin")
    set(CMAKE_INSTALL_LIBDIR "lib")
    set(CMAKE_INSTALL_INCLUDEDIR "include")
else()
    include(GNUInstallDirs)
endif()

# 查找依赖包
find_package(PostgreSQL REQUIRED)

# 查找 libpqxx
find_package(PQXX REQUIRED)

# 输出配置信息
message(STATUS "Building for platform: ${CMAKE_SYSTEM_NAME}")
message(STATUS "Compiler: ${CMAKE_CXX_COMPILER_ID}")
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")

# 添加子目录
add_subdirectory(src)

# 如果启用测试
option(BUILD_TESTS "Build tests" ON)
if(BUILD_TESTS)
    enable_testing()
    add_subdirectory(tests)
endif()

# 安装目标
install(TARGETS demo_app
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
    BUNDLE DESTINATION ${CMAKE_INSTALL_BINDIR}
)

# 包配置
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
    "${CMAKE_CURRENT_BINARY_DIR}/DemoProjectConfigVersion.cmake"
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY AnyNewerVersion
)

# CPack 配置 (可选打包)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)